//
//  HMHomeTableViewController.m
//  HowToDo
//
//  Created by Apple on 16/12/31.
//  Copyright © 2016年 KY. All rights reserved.
//

#import "HMHomeTableViewController.h"
#import "HMTodayHappyTalkController.h"
#import "HMHomeTableViewController.h"
#import "HMGoldSentenceViewCtr.h"
#import "HMHomeViewModel.h"
#import "HMHomeHeader.h"
#import "HMTopILView.h"
#import "HTDCarousel.h"
#import "HMHomeFreeAudioCell.h"
#import "HMHomeSpecialColumnCell.h"
#import "HMHomeTEDBookCell.h"
#import "HMHomeGuessLikeCell.h"
#import "HMHomeRandDataCell.h"
#import "HMHomeRecommendCell.h"
#import "HMHomeGoldSentenceCell.h"
#import "HMHomeTabSectionHeader.h"
#import "HMListenAnyTimeResModel.h"
//播放器控制器
#import "HMAudioPlayerController.h"
//天天长知识
#import "HMEveryDayViewCtr.h"
#import "HMBaseNavController.h"
//猜你喜欢，热门排行
#import "HMRecommendDetailVC.h"
//热门排行查看全部，十万个为什么；
//行业达人cell
#import "HMDetailsTableViewController.h"
//所有行业达人
#import "HMSpecialColumnListCtr.h"
//跳转search界面
#import "HMSearchTableViewController.h"
#import "HMEveryDayViewCtr.h"

@interface HMHomeTableViewController ()<UITableViewDelegate,UITableViewDataSource>
/**
 首页对应的viewModel
 */
@property(nonatomic,strong)HMHomeViewModel *homeViewModel;
/**
 展示数据的主列表视图
 */
@property(nonatomic,strong)UITableView *mainTab;
@property(strong,nonatomic)UIImageView *leftBarButtonImageView;
/**
 记录当前播放序号
 */
@property(nonatomic,assign)NSInteger  currentPlayIndex;
@property(nonatomic,assign)NSInteger rowCount;
@end
static NSString *freeAudioCellID = @"HomeFreeAudioCellID";
static NSString *specialColumnCellID = @"HomeSpecialColumnCellID";
static NSString *everyDayBookCellID = @"HomeEveryDayBookCellID";
static NSString *guessLikeCellID = @"HomeGuessLikeCellID";
static NSString *rankDataCellID = @"HomeRankDataCellID";
static NSString *recommendCellID = @"HomeRecommendCellID";
static NSString *goldStenceCellID = @"HomeGoldStenceCellID";
@implementation HMHomeTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupTableView];
    //请求数据
    [self loadData];
}
//设置mainTab相关
- (void)setupTableView
{
    //初始化
    self.currentPlayIndex = -1;
    self.navigationItem.title = @"首页";
    //隐藏分割线
    self.mainTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    //隐藏导航条
    self.mainTab.showsVerticalScrollIndicator = NO;
    //设置预估行高
    self.mainTab.estimatedRowHeight = 200;
    self.mainTab.rowHeight = UITableViewAutomaticDimension;
    //请求数据
    [self loadData];
    //设置头
    [self setHomeTableViewHeader];
    //注册cell
    [self registerHomeTabCell];
//-------------设置导航栏开始--------------------------------
    [super setupNavLeftItemsBySearch];
    [super setupNavRightItemsByOne];
//-------------设置导航栏结束--------------------------------
}
//注册cell的方法
- (void)registerHomeTabCell
{
    [self.mainTab registerClass:[HMHomeFreeAudioCell class] forCellReuseIdentifier:freeAudioCellID];
    
    [self.mainTab registerNib:[UINib nibWithNibName:@"HMHomeSpecialColumnCell" bundle:nil] forCellReuseIdentifier: specialColumnCellID];
    
    [self.mainTab registerNib:[UINib nibWithNibName:@"HMHomeTEDBookCell" bundle:nil] forCellReuseIdentifier:everyDayBookCellID];
    
    [self.mainTab registerClass:[HMHomeGuessLikeCell class] forCellReuseIdentifier:guessLikeCellID];
    [self.mainTab registerClass:[HMHomeRandDataCell class] forCellReuseIdentifier:rankDataCellID];
    
    [self.mainTab registerNib:[UINib nibWithNibName:@"HMHomeRCCell" bundle:nil] forCellReuseIdentifier:recommendCellID];
    
    [self.mainTab registerNib:[UINib nibWithNibName:@"HMHomeGoldSentenceCell" bundle:nil] forCellReuseIdentifier:goldStenceCellID];
}
- (void)setHomeTableViewHeader
{
    HMHomeHeader *header = [[HMHomeHeader alloc]init];
//    点击头部底部按钮的回调跳转
    __weak typeof(self)weakSelf = self;
    header.clickBtnCallBack = ^(HMTopILView* sender)
    {
        NSString *pushVcName = sender.pushVcName;
        
        Class class =  NSClassFromString(pushVcName);
        
        UIViewController* vc = [[class alloc]init];
        
        if ([vc isKindOfClass:[HMBaseViewController class]] || [vc isKindOfClass:[HMHomeTableViewController class]])
        {
            HMBaseViewController *tuhao = (HMBaseViewController *)vc;
            tuhao.programTypeID = sender.programTp_Id;
        }

        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    //点击轮播图
    header.clickCycleImg = ^(NSInteger index)
    {
        HTDCarousel* car = weakSelf.homeViewModel.homeCarousel[index];
        HMDetailsTableViewController* detail = [[HMDetailsTableViewController alloc]init];
        detail.tid = car.type_id;
        [weakSelf.navigationController pushViewController:detail animated:YES];
    };
    
   
    CGFloat height = 165;
    
    CGRect frame = self.mainTab.tableHeaderView.frame;
    
    frame.size.height = height;
    
    header.frame = frame;
    
    self.mainTab.tableHeaderView = header;
}
#pragma mark --dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.homeViewModel.homeData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //根据组坐标获取数组中对应的模型数组或者数据
    return [self.homeViewModel numberOfItemsHomeTabWithSection:section DataList:self.homeViewModel.homeData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //根据不同组坐标确定不同的cellID和对应的模型数据；
    NSString* cellId = [self.homeViewModel cellIdentifierWithSection:indexPath.section];
    //利用多态创建不同的cell
    HMHomeTabBaseCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    
    [self setModelToCell:cell IndexPath:indexPath WithHomeDataList:self.homeViewModel.homeData];
    
    return cell;
}

-(void)setModelToCell:(HMHomeTabBaseCell *)cell IndexPath:(NSIndexPath *) indexPath WithHomeDataList:(NSArray*)homeDataList
{
    switch (indexPath.section)
    {
        case HMHomeFreeAudioSection:
        {
            HMHomeFreeAudioCell * freeAudioCell = (HMHomeFreeAudioCell*)cell;
            freeAudioCell.freeAudios = self.homeViewModel.homeData[0];
            //点击事件的回调
            __weak typeof(self)weakSelf = self;
            freeAudioCell.clickBigPlayButtonBlock = ^(NSInteger index ,BOOL isPlaying)
            {
                [weakSelf clickBigPlayBtnWithIndex:index WithIsPlaying:isPlaying];
            };
        }
            break;
        case HMHomeSpecialColumnSection:
        {
            HMHomeSpecialColumnCell *specialColumnCell = (HMHomeSpecialColumnCell*)cell;
            //换一换的方法每次改组的数据每一条的序号数据加一；当最大时让你归零；
            specialColumnCell.specialColumn = self.homeViewModel.homeData[indexPath.section][indexPath.row + self.rowCount];
        }      
            break;
        case HMHomeEveryDayBookSection:
        {
            HMHomeTEDBookCell *everyDayBookCell = (HMHomeTEDBookCell *)cell;
            everyDayBookCell.edBook = self.homeViewModel.homeData[HMHomeEveryDayBookSection][indexPath.row];
        }
            break;
        case HMHomeGuessLikeSection:
        {
            HMHomeGuessLikeCell *guessLikeCell = (HMHomeGuessLikeCell *)cell;
#pragma mark 选择猜你喜欢对应item回调的方法；此处push到
            guessLikeCell.selectedItemCallBack = ^(NSIndexPath *indexPath)
            {
                HMRecommendDetailVC* recommendDetaiVc = [[HMRecommendDetailVC alloc]init];
                
               HTDGuessLike *guessLike = self.homeViewModel.homeData[HMHomeGuessLikeSection][indexPath.row];
                
                recommendDetaiVc.resource_id = guessLike.resource_id.description;
                [self.navigationController pushViewController:recommendDetaiVc animated:YES];
            };
            
            guessLikeCell.guessYouLikes = self.homeViewModel.homeData[HMHomeGuessLikeSection];
        }
            break;
        case HMHomeRankDataSection:
        {
            HMHomeRandDataCell  *randDataCell = (HMHomeRandDataCell *)cell;
#pragma mark --选择热门推荐对应item对应的回调
            randDataCell.selectedItemCallBack = ^(NSIndexPath * indexPath)
            {
                HMRecommendDetailVC* detailVc = [[HMRecommendDetailVC alloc]init];
                HTDRankData* rank = self.homeViewModel.homeData[HMHomeRankDataSection][indexPath.row];
                
                detailVc.resource_id = rank.resource_id.description;
            
                [self.navigationController pushViewController:detailVc animated:YES];
            };
            randDataCell.rankDataList = homeDataList[HMHomeRankDataSection];
            
        }
            break;
        case HMHomeRecommendSection:
        {
            HMHomeRecommendCell  *recommendCell = (HMHomeRecommendCell *)cell;
            recommendCell.imgUrlList = homeDataList[HMHomeRecommendSection];
        }
            break;
        case HMHomeGoldStenceSection:
        {
            HMHomeGoldSentenceCell  *goldSentenceCell = (HMHomeGoldSentenceCell *)cell;
            
            goldSentenceCell.sentenceInfo = homeDataList[HMHomeGoldStenceSection];
        }
            break;
        default:
            break;
    }
}

-(void)changeNewDataWithSection:(NSInteger)section
{
    if (section == HMHomeSpecialColumnSection)
    {
        self.rowCount ++;
        if (self.rowCount >= [self.homeViewModel.homeData[HMHomeSpecialColumnSection] count] -3 )
        {
            self.rowCount = 0;
        }
        
        [self.mainTab reloadData];
    }

}

- (void)loadData
{
//     __weak typeof(self) weakSelf = self;
    //在请求数据完成的回调中给各属性完成赋值，然后刷新
    [self.homeViewModel loadHomeDataFinished:^(NSError *error) {
        
        if (error != nil)
        {
             [self showTipViewWithName:nil andMessage:@"网络错误"];
        }else
        {
            [self loadDadaFinished];
        }
        
    }];
}

#pragma mark -- 点击资源名称播放对应的数据
- (void)clickBigPlayBtnWithIndex:(NSInteger)index WithIsPlaying:(BOOL)isplaying
{
   
    if (isplaying == NO)
    {
       dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[HMAudioPlayerController sharePlayer]stop];
       });
        NSLog(@"暂停/停止");
    }else
    {
        
        if (isplaying == YES && self.currentPlayIndex == index)
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
              [[HMAudioPlayerController sharePlayer]play];
            });
            
             NSLog(@"--继续第%zd条数据播放---", index);
        }else
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^
            {
                NSArray * audioList = self.homeViewModel.homeData[HMHomeFreeAudioSection];
                [[HMAudioPlayerController sharePlayer]setModelArray:audioList index:index];
            });
            
            NSLog(@"--新播放第%zd条数据---", index);
        
            self.currentPlayIndex = index;
        }
    }
    

}

//数据请求完成调用的方法；
-(void)loadDadaFinished
{
      __weak typeof(self) weakSelf = self;
    if (weakSelf.tipView) [weakSelf removeTipView];
    //轮播图模型转换数据
    NSMutableArray* temp = [NSMutableArray array];
    for (HTDCarousel* carousel in weakSelf.homeViewModel.homeCarousel)
    {
        [temp addObject:carousel.image_url];
    }
    HMHomeHeader* header =(HMHomeHeader*) weakSelf.mainTab.tableHeaderView;
    header.carouselList = temp.copy;
    //顶部分类选择按钮数据
    header.classfiList = weakSelf.homeViewModel.classifyList;
    //获取
    [weakSelf.mainTab endRefresh];
    //刷新
    [weakSelf.mainTab reloadData];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section != HMHomeSpecialColumnSection)
    {
        return nil;
    }
    UIButton *btn = [[UIButton alloc]init];
    btn.tag = section;
    NSString * footTitle = [NSString stringWithFormat:@"查看全部%zd条",[self.homeViewModel.homeData[section] count]];
    [btn setTitle:footTitle forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor whiteColor]];
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    //修改尾部按钮标题颜色
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickSectionFooterAction:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   return [self creatSectionHeaderWithIndexPath:section];
}
- (UIView *)creatSectionHeaderWithIndexPath:(NSInteger) section
{
    HMHomeTabSectionHeader* sectionHeader = [HMHomeTabSectionHeader initWithNib:@"HMHomeSectionHeader"];
    //设置当前组头的标记
    sectionHeader.section = section;
#pragma mark --组头的点击事件回调
    __weak typeof(self)weakSelf = self;
    sectionHeader.clickCurrentSectionHeader = ^(NSInteger currentSection)
    {
        //01.跳转到今今乐道
        [weakSelf pushToTHTVcWithSEction:currentSection];
        //02.天天长知识
        [weakSelf pushToEveryDayCtrWith:currentSection];
        //03.换一换changeCelldata
        [weakSelf changeNewDataWithSection:currentSection];
    };
    //隐藏不显示的组头
    BOOL ishidden = (section == HMHomeRecommendSection)?YES:NO;
    //设置组头的文字和属性
    NSDictionary* dic = [self.homeViewModel channelSectionInfoWithSectionName:section];
    NSString* name = dic[@"channelName"];
    NSString* function = dic[@"channelFunction"];
    NSString* iconName = dic[@"functionIcon"];
    [sectionHeader setChannelName:name FunctionName:function FunctionIcon:[UIImage imageNamed:iconName] BottomLineHidden:ishidden];
    //设置不同组的做头样式
    if (section == HMHomeSpecialColumnSection || section == HMHomeGuessLikeSection)
    {
        [sectionHeader takeIconImgFrontOfFunctionLable];
    }else if (section == HMHomeRecommendSection)
    {
        sectionHeader = nil;
    }
    return sectionHeader;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == HMHomeRecommendSection)
    {
        return 0.01;
    }
    return 54;
}
//设置组尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == HMHomeSpecialColumnSection)
    {
        return 44;
    }else if (section == HMHomeRankDataSection)
    {
        return 10;
    }
    return 0.01;
}
#pragma mark --用户交互代码区
//选中cell点击的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //跳转到今今乐道
    [self pushToTHTVcWithSEction:indexPath.section];
    //跳转到详情页面
    [self selectedSpecialCellWithIndexPath:indexPath];
    //查看更多金句
    [self lookGoldSentenceViewWith:indexPath];
}
-(void)pushToEveryDayCtrWith:(NSInteger)section
{
    if (section == HMHomeFreeAudioSection)
    {
        HMEveryDayViewCtr *everyDay = [[HMEveryDayViewCtr alloc] init];
        [self.navigationController pushViewController:everyDay animated:YES];
    }
}
//调用此方法当时所需要的组时就跳转页面
-(void)pushToTHTVcWithSEction:(NSInteger)section
{
    if (section == HMHomeEveryDayBookSection)
    {
        HMTodayHappyTalkController* thtVc = [[HMTodayHappyTalkController alloc]init];
        [self.navigationController pushViewController:thtVc animated:YES];
    }
}
#pragma mark --点击组尾查看更多
- (void)clickSectionFooterAction:(UIButton *)sender
{
    NSInteger section = sender.tag;
    if (section == HMHomeSpecialColumnSection)
    {
        NSArray <HTDSpecialColumn*>* scolumList = self.homeViewModel.homeData[HMHomeSpecialColumnSection];
        HMSpecialColumnListCtr* splistCtr = [[HMSpecialColumnListCtr alloc]init];
        splistCtr.splist = scolumList;
        [self.navigationController pushViewController:splistCtr animated:YES];
    }
}
#pragma mark-- 查看更多金句
-(void)lookGoldSentenceViewWith:(NSIndexPath*)indexPath
{
    if (indexPath.section == HMHomeGoldStenceSection)
    {
        HMGoldSentenceViewCtr* goldSen = [[HMGoldSentenceViewCtr alloc]init];
        [self.navigationController pushViewController:goldSen animated:YES];
    }
}
#pragma mark --选择行业达人对应的cell对应的方法
-(void)selectedSpecialCellWithIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == HMHomeSpecialColumnSection)
    {
        HMDetailsTableViewController* detailVc= [[HMDetailsTableViewController alloc]init];
         HTDSpecialColumn* specialColumn  = self.homeViewModel.homeData[HMHomeSpecialColumnSection][indexPath.row];
        detailVc.tid = specialColumn.tid;
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}
#pragma mark -- 懒加载
- (HMHomeViewModel *)homeViewModel
{
    if (!_homeViewModel)
    {
        _homeViewModel = [[HMHomeViewModel alloc]init];
    }
    return _homeViewModel;
}
//懒加载tabview
-(UITableView *)mainTab
{
    if (!_mainTab)
    {
        _mainTab = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _mainTab.dataSource = self;
        _mainTab.delegate = self;
        [self.view addSubview:_mainTab];
        //添加刷新控件
        [_mainTab addTableViewRefreshHeaderWhenPullToPerformAction:@selector(loadData)];
    }
    return _mainTab;
}

@end
